<template>
  <div v-loading="editLoading" element-loading-background="rgba(255, 255, 255, 0.6)" element-loading-text="保存中,请稍候">
    <request-detail v-if="detailInfo" :request-detail-info="detailInfo" :offerInfo="offerInfo"></request-detail>
    <el-row v-for="(creativeRequestDetail,index) in dataList.creativeRequestDetailList"
            class="detailList-body">
      <div>
        <request-edit-detail
          :user-role="userRole"
          :title="title"
          :offer-id="offerId"
          :get-platform="getPlatform"
          :userRole="userRole"
          :creativeRequestData="dataList"
          :creativeRequestDetail="creativeRequestDetail"
          :creativeRequestDetailIndex="index"
          ref="detailComponent"
        ></request-edit-detail>
        <div>
          <request-edit-prod
                      :platform="platform"
                      :offer-id="offerId"
                      title="product"
                      ref="prodComponent"
                      :user-role="userRole"
                      :creative-request-data="dataList"
                      :creative-request-detail="creativeRequestDetail"
                      :creative-request-detail-index="index"
          ></request-edit-prod>
        </div>
      </div>
    </el-row>
    <div class="btn-group">
      <el-button
        id="id-offer-componets-creativerequest-conmponents-request-edit-handleSubmit"
        size="medium"
        style="margin-right: 20px"
        type="primary"
        @click="handleSubmit(null)"
      >保存
      </el-button
      >
      <el-button id="" size="medium" @click="handlerClose">取消</el-button>
    </div>
  </div>
</template>

<script>
import requestForm from "./request-form";
import requestEditProd from "./request-edit-prod";
import requestDetail from "@/views/offer/components/creativeRequest-components/requestDetail";
import requestEditDetail from "./request-edit-detail";
import {
  getDetail as getCreativeRequestDetail,
  saveCreative as creativeRequestSubmit,
  getOfferDesigner,
  getOfferOptimizer
} from "@/api/offer/creativerequest";
import {getAllUser} from "@/api/user";

export default {
  name: "request-edit",
  components: {
    requestForm,
    requestEditProd,
    requestEditDetail,
    requestDetail,
  },
  props: {
    offerId: String,
    title: String,
    userRole: Object,
    close: Function,
    dataList: Object,
    offerInfo: Object,
    detailInfo: Object
  },
  created() {
    this.init();
  },
  data() {
    return {
      platform: "", //平台
      activeName: "creativeRequest", //tab
      initDetailList: [],
      editLoading: false,
      oldFinishedCreativeDemandStatusList: null,
    };
  },
  methods: {
    /**
     * 初始化显示列表
     */
    init() {
      let designers = [];
      let designerManager;
      let creativeType = [];
      let requester
      Promise.all([
        getAllUser({statusList: '0,1,2', isAll: true}).then((res) => {
          let allUserList = res.data.data;
          if (allUserList.length > 0) {
            let designersIdList = this.dataList.creativeRequest.designers.split(",");
            allUserList.map(item => {
              if (item.id === this.dataList.creativeRequest.designerManager) {
                designerManager = item.realName;
              }
              if (item.id === this.dataList.creativeRequest.requester) {
                requester = item.realName;
              }
              if (designersIdList.includes(item.id)) {
                designers.push(item.realName);
              }
            })
          }
        })
      ]).then(result => {
        if (result) {
          let checkedCreativeTypeList = [
            {id: "0", name: "图片"},
            {id: "1", name: "视频"},
          ]
          this.dataList.creativeRequest.creativeType.split(',').map(item => {
            checkedCreativeTypeList.map(it => {
              if (it.id === item) {
                creativeType.push(it.name)
              }
            })
          })
          this.initDetailList = [
            {label: 'offer', value: this.dataList.creativeRequest.offerName},
            {label: '需求方', value: requester},
            {label: '媒体', value: this.dataList.creativeRequest.platform},
            {
              label: '产品URL', value: {
                androidUrl: this.offerInfo.androidAppUrl,
                iosUrl: this.offerInfo.iosAppUrl,
                websiteUrl: this.offerInfo.websiteAppUrl,
              }
            },
            {label: '素材类型', value: creativeType.join(',')},
            {label: '设计师负责人', value: designerManager},
            {label: '设计师', value: designers.join("，")},
            {label: '交付日期', value: this.dataList.creativeRequest.expectedTime},
            {label: '制作日期', value: this.dataList.creativeRequest.planTime},
            {label: '实际完成时间', value: this.dataList.creativeRequest.actualTime},
          ];
        }
      })

      this.dataList.creativeRequestDetailList.forEach((detail) => {
        detail.activeName = 'creativeRequestDetail';
      });
      this.dataList.creativeRequestDetailList.forEach((detail) => {
        detail.finishedCreativeList.sort((a, b) => {
          if (a.demandIsProd != b.demandIsProd) {
            return b.demandIsProd - a.demandIsProd;
          }
          if (a.demandIsProd == 0) {
            return 0;
          }
          if ((a.status == 1 || a.status == 2) && (b.status == 1 || b.status == 2)) {
            return 0;
          }
          if (a.status == 1 || a.status == 2) {
            return 1;
          }
          if (b.status == 1 || b.status == 2) {
            return -1;
          }
          if (a.demandStatus == b.demandStatus) {
            return 0;
          }
          if (a.demandStatus == 3 && b.demandStatus != 3) {
            return -1;
          }
          if (a.demandStatus != 3 && b.demandStatus == 3) {
            return 1;
          }
          if (a.demandStatus == 2 && b.demandStatus != 2) {
            return 1;
          }
          if (a.demandStatus != 2 && b.demandStatus == 2) {
            return -1;
          }
          return 0;
        });
      });
      this.oldFinishedCreativeDemandStatusList = this.getProdCreativeList(this.dataList.creativeRequestDetailList, undefined);
    },

    getProdCreativeList(creativeRequestDetailList, idx) {
      let unconfirmedProdCreativeList = [];
      let passedProdCreativeList = [];
      let rejectProdCreativeList = [];
      if (creativeRequestDetailList != null) {
        creativeRequestDetailList.map((item, index) => {
          if (idx == undefined || idx == index) {
            item.finishedCreativeList.map(i => {
              if (i.demandIsProd == 1) {
                if (i.demandStatus != 2 && i.demandStatus != 3) {
                  unconfirmedProdCreativeList.push(i.id);
                }
                if (i.demandStatus == 2) {
                  passedProdCreativeList.push(i.id);
                }
                if (i.demandStatus == 3) {
                  rejectProdCreativeList.push(i.id);
                }
              }
            })
          }
        });
      }
      return {
        unconfirmed: unconfirmedProdCreativeList,
        passed: passedProdCreativeList,
        reject: rejectProdCreativeList,
      };
    },
    includeAll(aList, bList) {
      for (let i = 0; i < bList.length; i++) {
        if (!aList.includes(bList[i])) {
          return false;
        }
      }
      return true;
    },

    /**
     * 提交
     */
    handleSubmit(oldCreativeRequest) {
      let self = this;
      if (!oldCreativeRequest) {
        getCreativeRequestDetail(this.dataList.creativeRequest.id).then(res => {
          this.handleSubmit(res.data.data);
        });
        return;
      }
      let oldFinishedCreativeDemandStatusList = this.getProdCreativeList(oldCreativeRequest.creativeRequestDetailList, undefined);
      if (!(this.includeAll(oldFinishedCreativeDemandStatusList.unconfirmed, this.oldFinishedCreativeDemandStatusList.unconfirmed)
        && this.includeAll(oldFinishedCreativeDemandStatusList.reject, this.oldFinishedCreativeDemandStatusList.reject)
        && this.includeAll(oldFinishedCreativeDemandStatusList.passed, this.oldFinishedCreativeDemandStatusList.passed)
        && this.includeAll(this.oldFinishedCreativeDemandStatusList.unconfirmed, oldFinishedCreativeDemandStatusList.unconfirmed)
        && this.includeAll(this.oldFinishedCreativeDemandStatusList.passed, oldFinishedCreativeDemandStatusList.passed)
        && this.includeAll(this.oldFinishedCreativeDemandStatusList.reject, oldFinishedCreativeDemandStatusList.reject)
      )
      ) {
        this.$confirm('<div>成品素材已经发生变更</div><div style="color: red;">如果点击 ‘确认’，您刚编辑的内容将被放弃，系统将重新加载页面。</div>', '提示', {
          dangerouslyUseHTMLString: true,
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          beforeClose: (action, instance, done) => {
            if (action == 'confirm') {
              self.dataList = oldCreativeRequest;
              self.init();
            }
            done();
          }
        }).then(() => {
        }).catch(() => {
        }).finally(() => {
        })
        return;
      }

      for(let i=0;i<self.dataList.creativeRequestDetailList.length;i++) {
        let message = self.$refs.detailComponent[i].checkInput() || self.$refs.prodComponent[i].checkInput();
        if(message != null) {
          console.log(message);
          self.$message.warning(message);
          return;
        }
      }
      if (self.isSaving) {
        return;
      }
      self.isSaving = true;
      let files = null;
      if (self.dataList.creativeRequestDetailList[0].activeName == 'creativeRequestDetail') {
        files = self.$refs.detailComponent[0].getAppendFileList();
        for (let n = 0; n < self.dataList.creativeRequestDetailList.length; n++) {
          self.$refs.detailComponent[n].saveInput();
        }
      }
      if (self.dataList.creativeRequestDetailList[0].activeName == 'creativeRequestProd') {
        for (let n = 0; n < self.dataList.creativeRequestDetailList.length; n++) {
          self.$refs.prodComponent[n].saveInput();
        }
      }
      self.editLoading = true
      console.log(this.$refs.prodComponent)
      self.dataList.deletedFinishedIds = this.$refs.prodComponent[0].deletedFinishedIds.join(',')
      console.log(self.dataList)
      creativeRequestSubmit(self.dataList, files).then(res => {
        if (res.data.success) {
          self.$message({
            type: 'success',
            message: '操作成功!'
          })
        }
      }).finally(() => {
        self.isSaving = false;
        self.editLoading = false;
        self.handlerClose()
      })

    },
    /**
     * 关闭
     */
    handlerClose() {
      this.close();
    },
    /**
     * 获取form表单选中的平台
     */
    getPlatform(val) {
      this.platform = val;
    },
    /**
     * 切换Tabs
     */
    handleTabs(tab) {
    },
  },
};
</script>

<style scoped lang="scss">
/deep/ div.el-tabs__item.is-active {
  background-color: dodgerblue;
  color: white;
  border: 1px solid dodgerblue;
  border-radius: 10px;
}

/deep/ div.el-tabs__item {
  border: 1px solid dodgerblue;
  border-radius: 10px;
  margin-right: 5px;
  text-align: center;
  padding-left: 20px !important;
  padding-right: 20px !important;
}

.btn-group {
  display: flex;
  justify-content: flex-end;
  padding: 2em 0;
  margin-right: 3em;
}

.editDetail_title {
  margin: 0 auto;
  width: 80%;
  box-sizing: border-box;
  padding: 10px;
  background: #ECF0F1;
  border-radius: 10px;
  border: solid 1px #BDC3C7
}

.editDetail {
  font-size: 14px;
  margin-top: 0.3em;

  .editDetail_label {
    color: #00a2ff;
    font-weight: 500;
  }
}

.detailList-body {
  width: 100%;
  background-color: whitesmoke;
  border: 1px solid #e8e8e8;
  border-radius: 10px;
  margin-top: 3em;
  padding-top: 1em;
}
</style>
